package cn.mw.cmdb.listener;

import cn.mw.cmdb.entity.InstanceInfo;
import cn.mw.cmdb.entity.ModelInfo;
import cn.mw.cmdb.enums.ModelViewTypeEnum;
import cn.mw.cmdb.param.ContextAddListener;
import cn.mw.cmdb.param.ContextDeleteListener;
import cn.mw.cmdb.param.ContextEditorListener;
import cn.mw.cmdb.processor.ModelViewTypeContext;
import cn.mw.cmdb.processor.ModelViewTypeFactory;
import cn.mw.cmdb.processor.ModelViewTypeProccessor;
import cn.mw.cmdb.service.impl.CmdbServiceManage;
import cn.mw.cmdb.service.impl.CustomModelServiceImpl;
import cn.mw.microMonitorCommon.annotation.entity.AssetsAutops;
import cn.mw.microMonitorCommon.api.autops.AutopsAndAssetsService;
import cn.mw.microMonitorCommon.util.SpringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import static cn.mw.cmdb.enums.ModelViewTypeEnum.*;

/**
 * 外部接口调用数据同步
 */
@Service
@Slf4j
public class CommonInterfaceSyncHandle implements InstanceChangeEventLister {

    @DubboReference(check = false, timeout = 10000, mock = "true")
    private AutopsAndAssetsService autopsAndAssetsService;

    private static List<ModelViewTypeEnum> modelViewTypeList = Arrays.asList(cabinetView, UNumView);


    @Override
    public void addReceive(ContextAddListener contextListener) throws Exception {
        CmdbServiceManage cmdbServiceManage = SpringUtils.getBean(CmdbServiceManage.class);
        Object param = contextListener.getParam();
        if (param != null && param instanceof List) {
            List<InstanceInfo> instanceInfoList = (List<InstanceInfo>) param;
            //获取所有实例的模型Id
            Set<String> modelIds = instanceInfoList.stream().map(s -> s.getModelId()).collect(Collectors.toSet());
            CustomModelServiceImpl modelService = (CustomModelServiceImpl) cmdbServiceManage.getModelService(CustomModelServiceImpl.ID);
            //根据模型Id获取模型信息
            List<ModelInfo> modelInfoList = modelService.findByIds(new ArrayList<>(modelIds));
            //转成模型实体对应的map
            Map<ModelViewTypeEnum, List<String>> viewTypeModelIds = modelInfoList.stream().collect(Collectors.groupingBy(s -> s.getModelViewType() == null ? defaultView : s.getModelViewType(), Collectors.mapping(ModelInfo::getId, Collectors.toList())));
            for (Map.Entry<ModelViewTypeEnum, List<String>> entry : viewTypeModelIds.entrySet()) {
                ModelViewTypeEnum k = entry.getKey();
                List<String> v = entry.getValue();
                ModelViewTypeEnum viewType = k;
                List<String> modelIdList = v;
                //获取不同视图下的资产实例
                List<InstanceInfo> disInstanceList = instanceInfoList.stream().filter(s -> modelIdList.contains(s.getModelId())).collect(Collectors.toList());
                ModelViewTypeProccessor build = ModelViewTypeFactory.build(viewType);
                ModelViewTypeContext context = new ModelViewTypeContext();
                context.setParam(disInstanceList);
                context.setCmdbServiceManage(cmdbServiceManage);
                build.addInstanceHandle(context);


            }


        }


    }

    @Override
    public Object editorReceive(ContextEditorListener contextListener) throws Exception {
        log.info("into-CommonInterfaceSyncHandle-editorReceive::11");
        //模型视图策略处理
//        List list = mwModelViewTypeHandle(contextListener);
        List list = new ArrayList();
//        log.info("外部接口数据同步-CommonInterfaceSyncHandle:editorReceive");
        Object param = contextListener.getParam();
        log.info("into-CommonInterfaceSyncHandle-editorReceive::ContextEditorListener"+param);
        List<AssetsAutops> autopsList = new ArrayList<>();
        if(param!=null && param instanceof List){
            List<InstanceInfo> instanceList = (List<InstanceInfo>) param;
            for(InstanceInfo instanceInfo : instanceList){
                AssetsAutops assetsAutops = new AssetsAutops();
                assetsAutops.setAssetsId(instanceInfo.getId());
                assetsAutops.setAssetsName(instanceInfo.getInstanceName());
                assetsAutops.setAssetsIP(instanceInfo.getInBandIp());
                autopsList.add(assetsAutops);
            }
            log.info("外部接口数据同步-updateAssetsNameOrIP::"+autopsList);
            autopsAndAssetsService.updateAssetsNameOrIP(autopsList);
        }
        return null;
    }

    @Override
    public void deleteReceive(ContextDeleteListener contextListener) throws Exception {
        log.info("外部接口数据同步-CommonInterfaceSyncHandle:deleteReceive");
        CmdbServiceManage cmdbServiceManage = SpringUtils.getBean(CmdbServiceManage.class);
        long time1 = System.currentTimeMillis();
        Object param = contextListener.getParam();
        List<AssetsAutops> autopsList = new ArrayList<>();
        if(param!=null && param instanceof List){
            List<InstanceInfo> instanceList = (List<InstanceInfo>) param;
            for(InstanceInfo instanceInfo : instanceList){
                AssetsAutops assetsAutops = new AssetsAutops();
                assetsAutops.setAssetsId(instanceInfo.getId());
                assetsAutops.setAssetsName(instanceInfo.getInstanceName());
                assetsAutops.setAssetsIP(instanceInfo.getInBandIp());
                autopsList.add(assetsAutops);
            }
            autopsAndAssetsService.deteleAccountIp(autopsList);
        }
        long time2 = System.currentTimeMillis();
        log.info("deleteReceive::deteleAccountIp::耗时："+(time2-time1)+"ms");
    }


    private List mwModelViewTypeHandle(ContextEditorListener contextListener) throws Exception {
        CmdbServiceManage cmdbServiceManage = SpringUtils.getBean(CmdbServiceManage.class);
        Object param = contextListener.getParam();
        if (param != null && param instanceof List) {
            List<InstanceInfo> instanceInfoList = (List<InstanceInfo>) param;
            //获取所有实例的模型Id
            Set<String> modelIds = instanceInfoList.stream().map(s -> s.getModelId()).collect(Collectors.toSet());
            CustomModelServiceImpl modelService = (CustomModelServiceImpl) cmdbServiceManage.getModelService(CustomModelServiceImpl.ID);
            //根据模型Id获取模型信息
            List<ModelInfo> modelInfoList = modelService.findByIds(new ArrayList<>(modelIds));
            //转成模型实体对应的map
            Map<ModelViewTypeEnum, List<String>> viewTypeModelIds = modelInfoList.stream().collect(Collectors.groupingBy(s -> s.getModelViewType() == null ? defaultView : s.getModelViewType(), Collectors.mapping(ModelInfo::getId, Collectors.toList())));
            List listObj = new ArrayList<>();
            for (Map.Entry<ModelViewTypeEnum, List<String>> entry : viewTypeModelIds.entrySet()) {
                ModelViewTypeEnum k = entry.getKey();
                List<String> v = entry.getValue();
                ModelViewTypeEnum viewType = k;
                List<String> modelIdList = v;
                //获取不同视图下的资产实例
                List<InstanceInfo> disInstanceList = instanceInfoList.stream().filter(s -> modelIdList.contains(s.getModelId())).collect(Collectors.toList());
                ModelViewTypeProccessor build = ModelViewTypeFactory.build(viewType);
                ModelViewTypeContext context = new ModelViewTypeContext();
                context.setParam(disInstanceList);
                context.setCmdbServiceManage(cmdbServiceManage);
                Object obj = build.updInstanceHandle(context);
                listObj.add(obj);
            }
            return listObj;
        }
        return null;
    }
}
